<?php
/**
 * @title 24. 两两交换链表中的节点 - 迭代
 * @author start2004
 */

class ListNode {
    public $val = 0;
    public $next = null;
    function __construct($val) { $this->val = $val; }
}

class Solution {

    /**
     * @param ListNode $head
     * @return ListNode
     */
    function swapPairs($head) {
        /**
         * @since 2020-10-13 a->b->c->d, 交换b,c
         * @since 2020-10-13 a->c->b->d
         */
        $a = null;

        /**
         * @since 2020-10-13 迭代
         */
        $b = $head;
        while(($c=$b->next) !== null){
            $d = $c->next;
            $c->next = $b;
            $b->next = $d;
            if($a !== null){
                $a->next = $c;
            } else {
                $head = $c;
            }

            /**
             * @since 2020-10-13 下次迭代
             */
            $a = $b;
            $b = $d;
        }

        /**
         * @return
         */
        return $head;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.03_6.php
 */
$arr = [1,2,3,4,5,6,7];
$node = new ListNode($arr[count($arr)-1]);
for($i=count($arr)-2; $i>=0; $i--){
    $next = $node;
    $node = new ListNode($arr[$i]);
    $node->next = $next;
}

$datas = [
    $node,
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->swapPairs($data);
    print_r($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
